﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Project_1.Models;

namespace Project_1.Controllers
{
    public class MessageController : Controller
    {
        //
        // GET: /Message/
        private const string ConnectionString = "Data Source=(local);Initial Catalog=AnsBook;Integrated Security=SSPI";
        AnsBookContext db = new AnsBookContext(ConnectionString);

        public ActionResult SendMessage()
        {
            if (Session["Username"]!=null)
            {
                return View();
            }
            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public ActionResult SendMessage(Message message)
        {
            if (ModelState.IsValid)
            {
                var newmessage = new Message 
                { Sender = message.Sender,
                Receiver = message.Receiver,
                SentTime = DateTime.Now,
                Title = message.Title,
                Content = message.Content,
                Read = false };
                try
                {
                    db.Entry(newmessage).State = EntityState.Added;
                    db.SaveChanges();
                }
                catch (Exception)
                {
                    ViewBag.Error = "This user name does not exist";
                }
            }
            return View(message);
        }

    }
}
